import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login/Login'
import Reg from '@/views/Reg/Reg'
import Main from '@/views/Main/Main'
import store from '@/store'
import Home from '@/views/menus/Home/Home'
import UserInfo from '@/views/menus/User/UserInfo'
import UserAvatar from '@/views/menus/User/UserAvatar'
import UserPwd from '@/views/menus/User/UserPwd'
import ArtCate from '@/views/menus/Article/ArtCate'
import ArtList from '@/views/menus/Article/ArtList'


// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const routes = [
  {
    path: '/reg',
    component:Reg
  },
  {
    path: '/login',
    component:Login
  },
  {
    path: '/',
    component: Main,
    // 开启路由重定向
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: Home
      },
      {
        path: 'user-info',
        component: UserInfo
      },
      {
        path: 'user-avatar',
        component: UserAvatar
      },
      {
        path: 'user-pwd',
        component: UserPwd
      },
      {
        path: 'art-cate',
        component: ArtCate
      },
      {
        path: 'art-list',
        component: ArtList
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  const token = store.state.token
  if (to.path === '/login' || to.path === '/reg') {
    next()
  } else {
    // 访问的不是两个路径 需要看是否有token
    if (!token) {
      // 没有token就跳转到登录页面
      next('/login')
    } else {
      next()
    }
  }
})
export default router
